package com.hema.auction.fragment;

import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.adapter.MyPropertyAdapter;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.PropertyInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.widget.view.RefreshRecyclerView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

/**
 * 财产明细
 * author by john
 */

public class PropertyDetailFragment extends BaseFragment {

    @BindView(R.id.refresh_recycler_view)
    RefreshRecyclerView recyclerView;
    private MyPropertyAdapter adapter;
    private List<PropertyInfo> infos = new ArrayList<>();
    private int position;


    @Override
    protected int getLayout() {
        return R.layout.fragment_normal_refresh_recycler_view;
    }

    public static PropertyDetailFragment newInstance(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        PropertyDetailFragment fragment = new PropertyDetailFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void init() {
        super.init();
        recyclerView.setVerLayoutManager();
        position = getArguments().getInt("position");
        adapter = new MyPropertyAdapter(infos);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .colorResId(R.color.colorDivider).showLastDivider()
                .size(2).build());
        recyclerView.setOnRefreshListener(this);
        recyclerView.setRefresh(true);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        HttpManager.getInstance(getActivity()).getBalanceRecord(String.valueOf(position), this);
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        try {
            if (result.getInt("errcode") == 0) {
                List<PropertyInfo> newData = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<PropertyInfo>>() {
                }.getType());
                adapter.setNewData(newData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        recyclerView.setRefresh(false);
    }
}
